<template>
  <div>
    <div class="crumbs">
      <el-breadcrumb separator="/">
        <el-breadcrumb-item> <i class="el-icon-lx-cascades"></i> 档案列表 </el-breadcrumb-item>
      </el-breadcrumb>
    </div>
    <div class="container">
      <div class="handle-box">
        <!-- <el-button type="primary"
                   icon="el-icon-delete"
                   class="handle-del mr10"
                   @click="delAllSelection">批量删除</el-button> -->
        <el-select v-model="query.status"
                   placeholder="状态"
                   class="handle-select mr10">
                   <el-option label="全部" value=""></el-option>
          <el-option key="1"
                     label="在档"
                     value="1"></el-option>
          <el-option key="2"
                     label="出借"
                     value="0"></el-option>
        </el-select>
        <el-input v-model.trim="query.name"
                  placeholder="名称"
                  class="handle-input mr10"></el-input>
        <el-input v-model.trim="query.sn"
                  placeholder="编号"
                  class="handle-input mr10"></el-input>
        <el-button type="primary"
                   icon="el-icon-search"
                   @click="handleSearch">搜索</el-button>
        <el-button type="primary"
                   icon="el-icon-lx-roundadd"
                   @click="handleAdd">添加</el-button>
      </div>
      <el-table :data="tableData"
                border
                class="table"
                ref="multipleTable"
                @expand-change="expand"
                header-cell-class-name="table-header"
                row-key="id">
        <!-- <el-table-column type="selection"
                         width="55"
                         align="center"></el-table-column> -->
        <el-table-column type="expand">
          <template slot-scope="scope">
            <el-row :gutter="10">
              <el-col :span="9"
                      :offset="2">
                <el-table :header-cell-style="{ background: '#81d3f3 !important', color: 'white', textAlign: 'center' }"
                          :data="scope.row.lendList"
                          max-height="250"
                          :row-class-name="tableRowClassName">
                  <el-table-column prop="time"
                                   label="日期"
                                   width="180"> </el-table-column>
                  <el-table-column prop="person"
                                   label="姓名"
                                   width="180"> </el-table-column>
                  <el-table-column label="行为">
                    <template slot-scope="scope">
                      <el-tag :type="scope.row.in_out ? 'success' : 'danger'">{{
                                                scope.row.in_out ? '归还' : '出借'
                                            }}</el-tag>
                    </template>
                  </el-table-column>
                </el-table>
              </el-col>
            </el-row>
          </template>
        </el-table-column>
        <el-table-column prop="name"
                         label="名称"></el-table-column>
        <el-table-column label="编号"
                         prop="sn"> </el-table-column>
        <el-table-column label="状态"
                         align="center">
          <template slot-scope="scope">
            <el-tag :type="scope.row.status ? 'success' : 'danger'"
                    @click="addLend(scope.$index, scope.row)">{{
                            scope.row.status ? '在档' : '出借'
                        }}</el-tag>
          </template>
        </el-table-column>

        <el-table-column prop="create_time"
                         label="登记时间">
          <template slot-scope="scope">{{ scope.row.create_time | formatDate }}</template>
        </el-table-column>
        <el-table-column label="操作"
                         width="180"
                         align="center">
          <template slot-scope="scope">
            <el-button type="text"
                       icon="el-icon-edit"
                       @click="handleEdit(scope.$index, scope.row)">编辑</el-button>
            <el-button type="text"
                       icon="el-icon-upload"
                       class="thumb"
                       @click="handleThumb(scope.$index, scope.row)">大图</el-button>
            <el-button type="text"
                       icon="el-icon-delete"
                       class="red"
                       @click="handleDelete(scope.$index, scope.row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
      <div class="pagination">
        <el-pagination background
                       layout="total, prev, pager, next"
                       :current-page="query.pageIndex"
                       :page-size="query.pageSize"
                       :total="pageTotal"
                       @current-change="handlePageChange"></el-pagination>
      </div>
    </div>

    <!-- 添加弹出框 -->
    <el-dialog title="添加"
               :visible.sync="addVisible"
               width="30%">
      <el-form ref="addForm"
               v-model="addForm"
               label-width="70px">
        <el-form-item label="名称">
          <el-input v-model.trim="addForm.name"></el-input>
        </el-form-item>
        <el-form-item label="编号">
          <el-input v-model.trim="addForm.sn"></el-input>
        </el-form-item>
        <el-form-item label="登记时间">
          <el-date-picker type="date"
                          placeholder="选择日期"
                          v-model="addForm.create_time"
                          value-format="yyyy-MM-dd"
                          style="width: 100%;"></el-date-picker>
        </el-form-item>
      </el-form>
      <span slot="footer"
            class="dialog-footer">
        <el-button @click="addVisible = false">取 消</el-button>
        <el-button type="primary"
                   @click="saveAdd">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 大图弹出框 -->
    <el-image-viewer v-if="showViewer"
                     :on-close="
                () => {
                    showViewer = false;
                    thumbVisible = true;
                    urlList = [];
                }
            "
                     :url-list="urlList"
                     :initial-index="idx" />
    <el-dialog title="大图"
               :visible.sync="thumbVisible" width="400px">
      <el-upload ref="thumb"
                 class="upload-demo"
                 drag
                 action="index.php/index/upload"
                 :data="{ id }"
                 :on-remove="removeImg"
                 name="image"
                 :file-list="imageList"
                 :on-preview="viewer"
                 multiple
                 :on-success="imageSelect">
        <i class="el-icon-upload"></i>
        <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
      </el-upload>
      <span slot="footer"
            class="dialog-footer">
        <el-button @click="thumbVisible = false">关 闭</el-button>
      </span>
    </el-dialog>
    <!-- 添加出借记录 -->
    <el-dialog title="添加"
               :visible.sync="addLendVisible"
               width="30%">
      <el-form ref="addLendForm"
               :model="addLendForm"
               label-width="70px">
        <el-form-item label="姓名">
          <el-input v-model.trim="addLendForm.person"></el-input>
        </el-form-item>
        <el-form-item label="时间">
          <el-date-picker type="date"
                          placeholder="选择日期"
                          v-model="addLendForm.time"
                          value-format="yyyy-MM-dd"
                          style="width: 100%;"></el-date-picker>
        </el-form-item>
      </el-form>
      <span slot="footer"
            class="dialog-footer">
        <el-button @click="addLendVisible = false">取 消</el-button>
        <el-button :type="addLendForm.in_out ? 'success' : 'danger'"
                   @click="saveAddLend">{{
                    addLendForm.in_out ? '归还' : '出借'
                }}</el-button>
      </span>
    </el-dialog>
    <!-- 编辑弹出框 -->
    <el-dialog title="编辑"
               :visible.sync="editVisible"
               width="30%">
      <el-form ref="editForm"
               :model="editForm"
               label-width="70px">
        <el-form-item label="名称">
          <el-input v-model.trim="editForm.name"></el-input>
        </el-form-item>
        <el-form-item label="编号">
          <el-input v-model.trim="editForm.sn"></el-input>
        </el-form-item>
        <el-form-item label="登记时间">
          <el-date-picker type="date"
                          placeholder="选择日期"
                          v-model="editForm.create_time"
                          value-format="yyyy-MM-dd"
                          style="width: 100%;"></el-date-picker>
        </el-form-item>
      </el-form>
      <span slot="footer"
            class="dialog-footer">
        <el-button @click="editVisible = false">取 消</el-button>
        <el-button type="primary"
                   @click="saveEdit">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
// import { fetchData } from '../../api/index';
export default {
  name: 'basetable',
  components: {
    'el-image-viewer': () => import('element-ui/packages/image/src/image-viewer')
  },
  data () {
    return {
      query: {
        status: '',
        name: '',
        sn: '',
        pageIndex: 1,
        pageSize: 10
      },
      tableData: [],
      multipleSelection: [],
      delList: [],
      addVisible: false,
      editVisible: false,
      addLendVisible: false,
      pageTotal: 0,
      editForm: {},
      addLendForm: {},
      addForm: {},
      idx: -1,
      id: -1,
      imageList: [],
      thumbVisible: false,
      showViewer: false,
      urlList: [],
      thumbUrl: 'http://localhost/storage/'
    };
  },
  created () {
    this.getData();
  },
  methods: {
    viewer (image) {
      this.thumbVisible = false;
      this.showViewer = true;
      for (const [index, elem] of this.imageList.entries()) {
        if (elem.response.id == image.response.id) {
          this.idx = index;
        }
        this.urlList.push(elem.url);
      }
    },
    addLend (index, item) {
      this.idx = index;
      this.addLendVisible = true;
      this.addLendForm = { time: new Date().toLocaleDateString(), in_out: !item.status, dossier_id: item.id };
    },
    // 获取 页面数据
    async getData () {
      const { data: res } = await this.$http.get('fetchData', {
        params: this.query
      });
      this.tableData = res.tableData;
      this.pageTotal = res.pageTotal;
    },
    // 触发搜索按钮
    handleSearch () {
      this.$set(this.query, 'pageIndex', 1);
      this.getData();
      this.query={
        status: '',
        name: '',
        sn: '',
        pageIndex: 1,
        pageSize: 10
      }
    },
    // 删除操作
    handleDelete (index, row) {
      // 二次确认删除
      this.$confirm('确定要删除吗？', '提示', {
        type: 'warning'
      })
        .then(async () => {
          const { data: res } = await this.$http.get('deleteDossier', {
            params: row.id
          });
          if (res) {
            this.$message.success('删除成功');
            this.tableData.splice(index, 1);
          } else this.$message.error('删除失败');
        })
        .catch(() => { });
    },
    // 多选操作
    handleSelectionChange (val) {
      this.multipleSelection = val;
    },
    delAllSelection () {
      const length = this.multipleSelection.length;
      let str = '';
      this.delList = this.delList.concat(this.multipleSelection);
      for (let i = 0; i < length; i++) {
        str += this.multipleSelection[i].name + ' ';
      }
      this.$message.error(`删除了${str}`);
      this.multipleSelection = [];
    },
    // 编辑操作
    handleEdit (index, row) {
      this.idx = index;
      this.editForm = row;
      this.editVisible = true;
    },
    // 大图操作
    async handleThumb (index, row) {
      this.id = row.id;
      let { data: res } = await this.$http.get('fetchThumb?dossier_id=' + row.id);
      this.imageList = res;
      for (let item of this.imageList) {
        item.response = item;
        item.url = this.thumbUrl + item.url;
      }
      this.thumbVisible = true;
    },
    // 添加操作
    handleAdd () {
      this.addVisible = true;
      this.addForm.create_time = new Date().toLocaleDateString();
    },
    imageSelect (response, file, fileList) {
      file.url = this.thumbUrl + response.url;
      this.imageList.unshift(file);
    },
    //删除大图
    async removeImg (image) {
      try {
        const { data: res } = await this.$http.get('delThumb?id=' + image.id);
      } catch (error) {
        this.$message.error(error.message);
      }
      if (res === true) {
        this.$message.success('删除成功');
        this.imageList = this.imageList.filter(item => item.uid != image.uid);
      } else this.$message.error('删除失败');
    },
    async expand (row, lendList) {
      if (lendList.length) {
        for (const [index, item] of this.tableData.entries()) {
          if (item.id == row.id) {
            const { data: res } = await this.$http.get('fetchLends?dossier_id=' + row.id);
            // this.$refs.multipleTable.toggleRowExpansion(this.tableData[index],true)
            this.$set(this.tableData[index], 'lendList', res);
            // this.$refs.multipleTable.toggleRowExpansion(this.tableData[index])
            // this.$refs.multipleTable.toggleRowExpansion(this.tableData[index],true)
          }
        }
      }
    },
    // 保存添加
    async saveAdd () {
      const { data: res } = await this.$http.post('addDossier', this.addForm);
      if (res) {
        this.$message.success(`添加成功`);
        this.addForm = {};
        this.addVisible = false;
        await this.getData();
      } else {
        this.$message.error('添加失败');
        return;
      }
    },
    //保存添加lend
    async saveAddLend () {
      const { data: res } = await this.$http.post('addLend', this.addLendForm);
      if (res) {
        this.$message.success('添加成功');
        const { data: res } = await this.$http.get('fetchLends?dossier_id=' + this.addLendForm.dossier_id);
        this.$set(this.tableData[this.idx], 'lendList', res);
        this.$set(this.tableData[this.idx], 'status', this.addLendForm.in_out);
        // this.tableData[this.idx].lendList.unshift(this.addLendForm)
        this.$refs.multipleTable.toggleRowExpansion(this.tableData[this.idx], true);
      } else {
        this.$message.error('添加失败');
        return;
      }
      this.addLendForm = {};
      this.addLendVisible = false;
    },
    // 保存编辑
    async saveEdit () {
      const { data: res } = await this.$http.post('editDossier', this.editForm);
      if (res) {
        this.editVisible = false;
        this.$message.success(`修改第 ${this.idx + 1} 行成功`);
        this.$set(this.tableData, this.idx, this.editForm);
      } else {
        this.$message.error('修改失败');
        return;
      }
    },
    // 分页导航
    handlePageChange (val) {
      this.$set(this.query, 'pageIndex', val);
      this.getData();
    },
    //改变表格行颜色
    tableRowClassName: ({ row }) => (row.in_out ? 'success-row' : 'warning-row')
  }
};
</script>

<style scoped>
.handle-box {
    margin-bottom: 20px;
}

.handle-select {
    width: 120px;
}

.handle-input {
    width: 300px;
    display: inline-block;
}
.table {
    width: 100%;
    font-size: 14px;
}
.red {
    color: #ff0000;
}
.mr10 {
    margin-right: 10px;
}
.table-td-thumb {
    display: block;
    margin: auto;
    width: 40px;
    height: 40px;
}
.el-table >>> .warning-row {
    background: rgb(255, 226, 172);
}

.el-table >>> .success-row {
    background: #cbffad;
}
.thumb {
    color: rgb(17, 12, 15);
}
</style>
